import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const initState = {
	nasMaxUploadTaskNums: 5, // （云nas）最大支持的上传数量
	nasUploadingList: [], // （云nas）正在上传的列表
	nasDownloadList: [] // （云nas）正在下载的列表
};
const store = new Vuex.Store({
	// 简单深克隆
	state: JSON.parse(JSON.stringify(initState)),
	getters: {
		nasUploadingList: (state) => state.nasUploadingList,
		nasDownloadList: (state) => state.nasDownloadList,
	},
	mutations: {
		// （云nas）添加任务到上传列表中
		nasUploadingListAdd(state, data) {
			const existUpNum = state.nasUploadingList.filter(item => item.taskStatus == 'start').length;
			if (existUpNum <= state.nasMaxUploadTaskNums) {
				// 开始上传任务
				data.startUpload();
			}
			// 添加上传任务
			state.nasUploadingList.push(data);
			let key = 'nasUploadingList'
			// 缓存里面存储上传列表（解决app进程杀死或者手动退出app时，再次打开能够断点上传）
			uni.setStorageSync(key, JSON.stringify(state.nasUploadingList));
		},
		// （云nas）删除上传列表中的任务
		nasUploadingListDelete(state, data) {
			// 获取待上传的list,开始第一个的任务
			setTimeout(() => {
				let list = [...state.nasUploadingList];
				let pendingTasks = []
				let startTasks = []
				list.forEach((item, idx) => {
					if (item.taskStatus == 'pending') {
						pendingTasks.push(item)
					}
					if (item.taskStatus == 'start') {
						startTasks.push(item)
					}
					if (item.uid === data.uid) {
						state.nasUploadingList.splice(idx, 1);
					}
				});
				if (pendingTasks.length && startTasks.length < state.nasMaxUploadTaskNums + 1) {
					pendingTasks[0].startUpload();
				}
				let key = 'nasUploadingList'
				uni.setStorageSync(key, JSON.stringify(state.nasUploadingList));
			}, 500);
		},
		// （云nas）添加下载任务
		nasDownloadListAdd(state, data) {
			// 开始下载任务
			data.beforeDownload()
			state.nasDownloadList.push(data);
		},
		// （云nas）删除下载列表中的任务
		nasDownloadListDelete(state, data) {
			setTimeout(() => {
				state.nasDownloadList.forEach((item, idx) => {
					if (item.uid === data.uid) {
						state.nasDownloadList.splice(idx, 1);
					}
				});
			}, 1000);
		},
	},
	actions: {
		NASUPLOADINGLIST_ADD({
			commit
		}, data) {
			commit("nasUploadingListAdd", data);
		},
	},
});

export default store;
